<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2019/1/22
 * Time: 1:55 PM
 */

namespace api\models;


use common\models\Goods;
use api\models\Image;

class Good extends Goods
{
    public function fields()
    {
        return [
            'id',
//            'img'=>function($model){
//                /**
//                 * @var Good $model
//                 */
//                return Image::findOne($model->img0->id)->imageurl;
//            },
            'title',
            'color',
            'price',
            'availability_period',
            'availability_num',
        ];
    }


    public static function useGood($user_id, $good_id)
    {
        $good       = Good::findOne($good_id);
        $assignment = VipAssignment::findOne(['item_name' => $good->right0->item, 'user_id' => $user_id]);
        if ($assignment->availability_num > 0 && $assignment->expired_time > time()) {
            $assignment->availability_num--;
        } else {
            $assignment->delete();
            return false;
        }
        if ($assignment->save()) {
            return true;
        } else {
            return false;
        }
    }

    public static function canUseGood($user_id, $good_id)
    {
        $good       = Good::findOne($good_id);
        $assignment = VipAssignment::findOne(['item_name' => $good->right0->item, 'user_id' => $user_id]);
        if ($assignment->availability_num > 0 && $assignment->expired_time > time()) {
            return true;
        } else {
            return false;
        }
    }


}